package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.common.vo.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.model.OrderInfo;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service(version = "1.0",interfaceClass = OrderService.class)
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private JedisPool jedisPool;
    @Resource
    private OrderSettingMapper orderSettingMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private OrderMapper orderMapper;

    @Override
    public Result send(String telephone) {
        /**
         * 1. 发验证码 肯定要有验证码
         * 2. 给用户发短信 telephone 短信平台
         * 3. 验证码存在redis里面，设置一个过期时间，短信验证码的过期时间
         */
        int code = 123456;
//        int code = RandomUtils.nextInt(100000, 999999);
        System.out.println("发短信手机号:"+telephone+",验证码:"+code);
        //线程
//        boolean isSend = sendSms(telephone,code);
        boolean isSend = true;
        if (isSend){
            Jedis resource = jedisPool.getResource();
            resource.setex("ORDER_"+telephone,300,String.valueOf(code));
            if (resource != null) {
                resource.close();
            }
        }
        return Result.success(null);
    }

    @Override
    public Result submit(OrderInfo orderInfo) {
        //校验验证码
        String validateCode = orderInfo.getValidateCode();
        Jedis resource = jedisPool.getResource();
        String redisCode = resource.get("ORDER_"+orderInfo.getTelephone());
        if (redisCode == null || !redisCode.equals(validateCode)){
            return Result.fail(-999,"验证码不正确");
        }
        if (resource != null) {
            resource.close();
        }

        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        //mysql 8 Date进行查询 不支持 2021-11-02 00:00：00
        OrderSetting orderSetting = orderSettingMapper.findOrderSettingByDateStr(orderInfo.getOrderDate());
        if (orderSetting == null){
            return Result.fail(-999,"当前日期不能进行预约");
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        Integer number = orderSetting.getNumber();
        Integer reservations = orderSetting.getReservations();
        if (reservations >= number){
            return Result.fail(-999,"预约已满");
        }
        //
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String orderDate = orderInfo.getOrderDate();
        Integer setMealId = orderInfo.getSetMealId();
        String telephone = orderInfo.getTelephone();
        Member member = memberMapper.findMemberByPhone(telephone);
        if (member != null){
            //判断是否重复预约
            Integer memberId = member.getId();
            Order order = this.orderMapper.findOrder(memberId,orderDate,setMealId);
            if (order != null){
                return Result.fail(-999,"重复预约");
            }
        }

        //
        //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if (member == null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setIdCard(orderInfo.getIdCard());
            member.setName(orderInfo.getName());
            member.setSex(orderInfo.getSex().toString());
            member.setRegTime(new Date());
            this.memberMapper.save(member);
        }

        Order order = new Order();
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(setMealId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            order.setOrderDate(simpleDateFormat.parse(orderDate));
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.fail();
        }
        order.setMemberId(member.getId());
        this.orderMapper.save(order);

        //
        //5、预约成功，更新当日的已预约人数
//        orderSetting.setReservations(orderSetting.getReservations() + 1);
        this.orderSettingMapper.updateReservations(orderSetting.getId());

        return Result.success(order.getId());
    }

    @Override
    public Result findById(Integer id) {
        Map map = this.orderMapper.findById(id);
        //时分秒时间 英文时间
        Date orderDate = (Date) map.get("orderDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        map.put("orderDate",simpleDateFormat.format(orderDate));
        return Result.success(map);
    }

    private boolean sendSms(String telephone, int code) {
        //短信平台
        RestTemplate restTemplate = new RestTemplate();

        Map<String, String> params = new HashMap<>();
        params.put("sid","0c71daeb7f24a6ef768cb00b132c5624");
        params.put("token","38c5b2f652edec2cd5d7d26e58ab510e");
        params.put("appid","70cabdc8fa3349429417d0580bcead2f");
        params.put("templateid","564697");
        params.put("param",code+","+300);
        params.put("mobile",telephone);
        params.put("uid","1111");
        ResponseEntity<Map> responseEntity = restTemplate.postForEntity("https://open.ucpaas.com/ol/sms/sendsms", params, Map.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()){
            Map body = responseEntity.getBody();
            String statusCode = body.get("code").toString();
            if ("000000".equals(statusCode)){
                System.out.println("发短信手机号:"+telephone+",验证码:"+code);
                return true;
            }
            System.out.println(body.get("msg"));
            log.info("发短信返回的信息:{}",body.get("msg"));
        }
        return false;
    }
}
